import React, { useState, useImperativeHandle, useRef } from "react";

export interface mapType {
  initMap: (Lat?: number, Lng?: number) => void;
  addPoint: (arr: {Lat: number, Lng: number}[]) => void;
  handleSearch: (keyword: string, cb: (e: any) => void) => void;
  instance: any;
}

// 地图文档https://lbs.qq.com/webApi/javascriptGL/glGuide/glMarker

export default React.forwardRef(
  (
    {
      handleClick,
      ...otherProps
    }: {
      handleClick?: (e: any) => void;
    } & React.AllHTMLAttributes<HTMLDivElement>,
    ref
  ) => {
    const map = useRef<any>();
    const [markerLayer, setMarkerLayer] = useState<any>();

    useImperativeHandle(ref, () => ({
      initMap,
      addPoint,
      handleSearch,
      instance: map.current,
    }));

    const initMap = (Lat: any = 30.28802, Lng: any = 120.002059) => {
      if (map.current || !window.TMap) return;
      map.current = new window.TMap.Map(
        document.getElementById("qqmapIdComponent"),
        {
          center: new window.TMap.LatLng(Lat, Lng), //设置地图中心点坐标
          zoom: 17.2, //设置地图缩放级别
          pitch: 0,
          rotation: 0,
        }
      );
      map.current.on("click", (e: any) => {
        handleClick?.(e);
      });
      setMarkerLayer(new window.TMap.MultiMarker({ map: map.current }));
    };

    const addPoint = (arr: {Lat: number, Lng: number}[]) => {
      markerLayer.setGeometries([]);
      markerLayer.add(arr.map((item,index) => {
        return {
          id: index + 1,
          position: new window.TMap.LatLng(item.Lat, item.Lng),
        }
      }));
    };

    const handleSearch = (keyword: string, cb: () => any) => {
      const search = new window.TMap.service.Search({ pageSize: 10 });
      var suggest = new window.TMap.service.Suggestion({
        pageSize: 10, // 返回结果每页条目数
        region: keyword, // 限制城市范围
        regionFix: true, // 搜索无结果时是否固定在当前城市
      });
      if (keyword) {
        suggest
          .getSuggestions({
            keyword: keyword,
            location: map.current.getCenter(),
          })
          .then(cb)
          .catch(() => {
            console.log("出错了");
          });
      }
    };
    return (
      <div
        style={{ width: 300, height: 300 }}
        {...otherProps}
        id="qqmapIdComponent"
      ></div>
    );
  }
);
